package com.xjnt.base.support.admin.validator;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;

import com.google.common.collect.ImmutableList;
import com.jfinal.core.Controller;
import com.xjnt.base.support.admin.entity.Dictionary;
import com.xjnt.frameworks.core.BaseValidator;

public class DictionaryValidator extends BaseValidator {

	private static final List<String> validMethod = ImmutableList.of(
			"doSave",
			"doUpdate"
			);
	@Override
	protected void validate(Controller c) {
		Method method = getActionMethod();
		String[] methods = validMethod.toArray(new String[]{});
		Arrays.sort(methods);
		if(Arrays.binarySearch(methods, method) > -1){
			setShortCircuit(true);
			Dictionary dictionary = c.getModel(Dictionary.class);
			if (dictionary != null) {
				int type = dictionary.getInt(Dictionary.TYPE);
				String modelName = dictionary.getModelName();
				String field = "";
				String errorKey = "";
				switch (type) {
				case 0:
					field = modelName + "." + Dictionary.NAME;
					errorKey = modelName + "-" + Dictionary.NAME;
					validatorIsChinese(field, errorKey, "目录名称不能为空，且必须是中文");
					field = modelName + "." + Dictionary.CODE;
					errorKey = modelName + "-" + Dictionary.CODE;
					validatorIsCode(field, errorKey, "目录编码不能为空，由英文字母、数字、下划线、横杠，格式为 XXXX-XXXX");
					break;
				default:
					field = modelName + "." + Dictionary.NAME;
					errorKey = modelName + "-" + Dictionary.NAME;
					validateRequiredString(field, errorKey, "字典名称不能为空");
					field = modelName + "." + Dictionary.VALUE;
					errorKey = modelName + "-" + Dictionary.VALUE;
					validateRequiredString(field, errorKey, "字典值不能为空");
					break;
				}
			}
		}
	}

	@Override
	protected void handleError(Controller c) {
		Method method = getActionMethod();
		String[] methods = validMethod.toArray(new String[]{});
		Arrays.sort(methods);
		if(Arrays.binarySearch(methods, method) > -1){
			c.renderJson(getValidMsg());
		}
	}

}
